import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class MyBlockingQueue {
    private Integer[] date = null;
    private int size = 0;
    private int head = 0;
    private int tail = 0;

    public MyBlockingQueue(int capacity) {
        date = new Integer[capacity];
    }

    public void put(Integer elem) throws InterruptedException {
        synchronized (this) {
            while(size >= date.length) {
                this.wait();
            }
            date[tail] = elem;
            tail++;
            if(tail >= date.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }

    public Integer take() throws InterruptedException {
        synchronized (this) {
            while(size == 0) {
                this.wait();
            }
            Integer ret = date[head];
            head++;
            if(head >= date.length) {
                head = 0;
            }
            size--;
            this.notify();
            return ret;
        }
    }

}

public class demo16 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        //生产者 消费者模型

        Thread producer = new Thread(()->{
            int n = 0;
            while(true) {
                try {
                    queue.put(n);
                    System.out.println("加入元素: " + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"producer");

        Thread consumer = new Thread(()->{
            while(true) {
                try {
                    int n = queue.take();
                    System.out.println("处理元素: " + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"consumer");
        producer.start();
        consumer.start();
    }
}
